
/**
 * opts={
 * 		type:"",//type == "weibo" || type == "email" || type == "letter" //打开窗口时，默认显示窗口
 * 		content:"",//要分享的内容
 * 		title:"",//显示的标题
 *      qq_title:"",  //QQ平台专用
		qq_comment:"",  //QQ平台专用
		qq_summary:"",  //QQ平台专用
		qq_imgurl:"",  //QQ平台专用
		pid:,//活动id
		qid:,//问题id
		aid:,//答案id
 * }
 */
var DzqShare = function(opts){
	
	if(DZQCheckForUser())
		return false;
	
	var con_type = 1;
	if(window.location.href.indexOf("/party/") >= 0){
		con_type = 2;
	}
	var url = Constans.BASE_PATH+"weibo/shareweibo!opensharewin.action?type="+con_type+"&pid="+(opts.pid?opts.pid:0)+"&qid="+(opts.qid?opts.qid:0)+"&aid="+(opts.aid?opts.aid:0)+"&time="+(new Date().getTime());
	if(opts.loadUrl != null && opts.loadUrl != ""){
		url = opts.loadUrl;
	}
	var title = "分享";
	if(opts.title != null && opts.title != ""){
		title = opts.title;
	}
	
	// 窗口
	new DzqWin({
		loadUrl : url,
		title : title,
		afterFun : function() {
			initShareWin(opts);
		}
	});
	
	//初始化分享窗口
	function initShareWin(opts) {
		
		var type = opts.type;
		if (type == "weibo" || type == "email" || type == "letter") {// 分享微博,邮件,站内信分享
			//changeLabelClass("tb-webshare-weibo");
			//showContentDiv("tb-webshare-weibo-bind-content");
			//clickChangeLabelClass("tb-webshare-weibo-bind-content");
			
			changeLabelClass(type);
			showContentDiv("tb-webshare-"+type+"-content");
			clickChangeLabelClass(opts);
			
			var content = "";
			content = getDefContent(opts);
			
			$("#tb-webshare-"+type+"-content").find("textarea").val(content);
			
			if(type == "letter"){
				/*
				var $users = $("#add_share_usergs");
				sendInnerUserLisObj = $users.wendaDropDrownList({
					"width":395,
					"top":$users.parent().offset().top+$users.parent().height()+170,
					"left":$users.parent().offset().left,
					"searchFun":"searchSiteInnerUsers"
					//"enterFun":"addUsersHtml"
					});
				*/
			}
			
		}else{//分享答案窗口
			aid = type;
			type = "weibo";
			changeLabelClass(type);
			showContentDiv("tb-webshare-"+type+"-content");
			clickChangeLabelClass(aid);
			
			var content = "";
			content = getDefContent(opts,aid);
			$("#tb-webshare-"+type+"-content").find("textarea").val(content);
			
		}

		modaldialogOper(opts.title);
		bindTextareKeyUp($("#tb-webshare-weibo-content").find("textarea"));
		bindTextareKeyUp($("#tb-webshare-letter-content").find("textarea"));
		bindTextareKeyUp($("#tb-webshare-email-content").find("textarea"));
		
		remainlen = Wenda.remainLen(content,140,"cn");
		$("#weibo-character-count").text(remainlen);
		
		$("#share_question").find("a[name='send']").bind("click",function(){
			var $parent = $(this).parent().parent();
			var content = $parent.find("textarea").val();
			var type = $parent.attr("id");
			var email = "";
			var uids = "";
			var weibo = "";
			
			
			// 邮件分享
			if(type.indexOf("email") > -1){
				if(!checkAuth(DZQ_ACTIONS.SHARE_EMAIL)){
					return;
				}
				
				var $mail = $parent.find("input[name='email']");
				email = $mail.val();
				if(!checkLength( $mail , "邮箱", 6, 80 ))return;
				//email_Regexp 在util.js中定义
				if(!checkRegexp( $mail, email_Regexp, "请输入正确邮箱，例如：example@dianziq.com" ))return;
			}
			
			// 站内信分享
			else if(type.indexOf("letter") > -1){
				if(!checkAuth(DZQ_ACTIONS.SHARE_SITE)){
					return;
				}
				/*
				$("#addQ_tagList").find("a").each(function(){
					var uidstr = $(this).attr("id");
					uids += uidstr.split("-")[1] + ",";
				});
				if(uids == "" || uids.length == 0){
					Wenda.alert("请输入要分享的站内用户");
					return;
				}
				*/
			}
			// 微博分享
			else if(type.indexOf("weibo") > -1){
				if(!checkAuth(DZQ_ACTIONS.SHARE_WEIBO)){
					return;
				}
				
				 $parent.find("input[type='checkbox']").each(function(){
					 if(this.checked){
						 weibo += this.value + "-";
					 }
					 
				 });
				 if(weibo.length > 0){
					 weibo = weibo.substring(0,weibo.length-1);
				 }
				 if(Wenda.realLength(content) > 280){
					 var remainlen = Wenda.remainLen(content,140,"cn");
					 Wenda.alert("你输入的内容已经超出了"+(-remainlen)+"个字");
					 return;
				}
			}
			
			if($.trim(content).length > 0){
				//shareQAEmail(content,qid,aid,email,uids,weibo);
				shareQAEmail(content,opts.qid,opts.aid,email,uids,weibo,opts.pid);
			}else{
				Wenda.alert("请输入分享内容");
			}
			
		});
	}

	/**
	 * 共享问题对话框
	 * 
	 * @param showID
	 *            要显示的内容id
	 */
	function changeLabelClass(type) {
		$("#share_question ul > li a ").removeClass().addClass("xpm");
		$("#tb-webshare-" + type).addClass("xpm xom");
	}
	
	/**
	 * 共享问题对话框
	 * 
	 * @param showID
	 *            要显示的内容id
	 */
	function showContentDiv(showID) {
		$("#share_question").children("div").css("display", "none");
		$("#" + showID).css("display", "block");
	}
	
	/**
	 * 共享问题对话框
	 * 
	 * @param showID
	 *            要显示的内容id
	 */
	function clickChangeLabelClass(opts) {
		$("#share_question ul > li a ").bind("click", function() {
			$("#share_question ul > li a ").removeClass().addClass("xpm");
			$(this).addClass("xpm xom");
			var showID = $(this).attr("id");
			if (showID.indexOf("sina") > 0) {
				showContentDiv(showID + "-bind-content");
			} else {
				showContentDiv(showID + "-content");
				if(showID.indexOf("letter") > -1){
					/*
					var $users = $("#add_share_usergs");
					sendInnerUserLisObj = $users.wendaDropDrownList({
						"width":395,
						"top":$users.parent().offset().top+$users.parent().height(),
						"left":$users.parent().parent().offset().left,
						"searchFun":"searchSiteInnerUsers"
						//"enterFun":"addUsersHtml"
						});
					$dzqobjtip =  $("#add_share_usergs").parent();
					scrollEvent = "sendInnerUserLisObj.setConfig({\"top\":$dzqobjtip.offset().top+$dzqobjtip.height(),\"left\":$dzqobjtip.parent().offset().left})";
					//console.log(scrollEvent);
					*/
				}
			}
			var content = "";
			if(showID)
				opts.type = showID.split("-")[2];
			
			content = getDefContent(opts);
			$("#"+showID+"-content").find("textarea").val(content);
		});
	}
	/**
	获取默认的分享描述
	*/
	function getDefContent(opts,answer){
		var type = opts.type;
		
		var qtitle = $("#q_title").val();
		var content = "";
		if(typeof opts.content == "function"){
			content = opts.content(type,opts.aid);
		}else{
			content = opts.content;
		}
		if( 0 > type.indexOf("weibo") && Wenda.realLength(content) > 280){//非微博分享
			content = Wenda.substr(content,276,"...");
		}else if(type.indexOf("weibo")>=0 ){//微博分享
			var sinaShortUrl = $("#sinaShortUrl").val();
			/**计算url长度时的算法*/
			if(Wenda.realLength(content) > 270){
				content = Wenda.substr(content,260,"...") + " "+sinaShortUrl;
			}else{
				content = content + " "+sinaShortUrl;
				var remainlen = Wenda.remainLen(content,140,"cn");
				if(remainlen > 17){
					content = content + " (分享自@电子圈)";
				}
			}
		}
		
		//初始化设置内容框高度
		//setTextareaHeight(content,$("#"+type+"_content"));
		Wenda.textareaAutoHeight(content,$("#"+type+"_content"));
		
		return content;
	}

	function bindTextareKeyUp($obj){
		$obj.bind("keyup",function(e){
			var content = $(this).val();
			var remainlen = Wenda.remainLen(content,140,"cn");//计算剩下的字节数
			
			//textarea的宽度和高度要比实际少4px
			//setTextareaHeight(content,$obj);
			
			Wenda.textareaAutoHeight(content,$obj);
			
			if(remainlen >= 0){
				$("#weibo-character-count").text(remainlen);
				$("#length").show();
				$("#beyond").hide();
			}else{
				$("#weibo-character-count-beyond").text(-remainlen);
				$("#beyond").show();
				$("#length").hide();
			}
		});
	}
	function shareQAEmail(content,qid,aid,email,uid,weibos,pid){
		
		if(weibos.length > 1){
			//var title = $("#q_otitle").val();
			var title = opts.qq_title==null?"":opts.qq_title;
			var comment = opts.qq_comment==null?"":opts.qq_comment;
			var summary = opts.qq_summary==null?"":opts.qq_summary;
			var imageurl = opts.qq_imgurl==null?"":opts.qq_imgurl;
			/*if(weibos != null && (weibos.indexOf("sns") >= 0)){
				comment = "我在电子圈上发现了非常好的问题："+title;
				imageurl = "http://www.dianziq.com/wenda/img/biglogo.png";
				if(aid > 0 || (aid != null && aid != "" )){
					var author = $("#aa-"+aid).find("h3").find("a[name='name']").text();
					summary = "@"+author+":"+$("#aa-"+aid).find("label[name='content']").text();
					summary = Wenda.substr(summary,156,"...");
				}else{
					summary = $("#q_content").val();
					summary = Wenda.substr(summary,156,"...");
				}
				summary = encodeURIComponent(summary);
				comment = encodeURIComponent(comment);
				title = encodeURIComponent(title);
			}*/
			//alert(weibos+" | " +imageurl +" | "+summary+" | "+comment);
			Wenda.post(Constans.BASE_PATH+"weibo/shareweibo!shareWeibo.action",{"messages":content,"weibos":weibos,"qid":qid,"aid":aid,"pid":pid,"type":con_type,"title":title,"summary":summary,"comment":comment,"imageurl":imageurl},function(data){
				qid=qid|0;
				if(data.messages){
					if(data.messages.indexOf("sina-0") >= 0 && data.messages.indexOf("qqsns-0") >= 0){
						Wenda.alert("微博分享成功");
					}
					else if(data.messages.indexOf("sina") >= 0){
						if(data.messages.indexOf("sina-0") >= 0){
							Wenda.alert("新浪微博分享成功");
						}else if(data.messages.indexOf("21319") >= 0){
							//Wenda.alert("授权关系已经被解除,请到“设置-->账号绑定”重新授权");
							Wenda.alert("授权关系已经被解除,点击<b><a href='javascript:;' data-href='"+Constans.BASE_PATH+"weibo/openBrower.action?state=3&weiboType=weibo@sina&qid="+qid+"' onclick=\"javascript:$('#dialog-message').remove();weiboAuthWin(this)\">重新授权</a></b>");
						}else if(data.messages.indexOf("21327") >= 0||data.messages.indexOf("21315") >= 0
								||data.messages.indexOf("21501") >= 0||data.messages.indexOf("21332") >= 0){
							//ec==21327||ec==21315||ec==21501||ec==21319||ec==21332
							//21327 ： token过期, 21501 ： access_token 无效, 21315 ： Token已经过期, 21319 ： 授权关系已经被解除 ,21332 ： access_token 无效 
							//Wenda.alert("授权已经过期或无效,请到“设置-->账号绑定”重新授权");
							Wenda.alert("授权已经过期或无效,点击<b><a href='javascript:;' data-href='"+Constans.BASE_PATH+"weibo/openBrower.action?state=3&weiboType=weibo@sina&qid="+qid+"' onclick=\"javascript:$('#dialog-message').remove();weiboAuthWin(this)\">重新授权</a></b>");
						}else if(data.messages.indexOf("20019") >= 0){
							Wenda.alert("重复提交内容");
						}else{
							Wenda.alert("新浪微博分享失败");
						}
					}
					/*
					else if(data.messages.indexOf("qqwb") >= 0){
						if(data.messages.indexOf("qqwb-0") >= 0){
							Wenda.alert("腾讯微博分享成功");
						}else{
							Wenda.alert("腾讯微博分享失败");
						}
					}*/
					else if(data.messages.indexOf("qqsns") >= 0){
						if(data.messages.indexOf("qqsns-0") >= 0){
							Wenda.alert("QQ分享成功");
						}else{
							Wenda.alert("QQ分享失败");
						}
					}else{
						Wenda.alert("分享完成");
					}
				}
				
//				var msg = data.messages.split("|");
//				if(msg[0] == "success"){
//					if(msg[1] == "100030"){
//						Wenda.alert("你的QQ相关接口未开放权限");
//					}else if(msg[1] == '0'){
//						Wenda.alert("分享成功");
//					}else {
//						Wenda.alert("分享失败");
//					}
//				}else{
//					Wenda.alert("分享失败");
//				}
				Wenda.closeWin();
			});
		}else{
			if(email != null && email.length > 0){
				Wenda.post(basePath+"json/qdetailJsonAction!shareEmail.action",{"qid":qid,"messages":content,"aid":aid,"email":email,"pid":pid,"touserid":uid,"weibos":weibos},function(data){
					if(data.messages == "success"){
						Wenda.alert("分享发送成功");
					} else if (data.messages == 'no_choose_weibo_style') {
						Wenda.alert("请选择微博的种类");
					}else{
						Wenda.alert("分享发送失败");
					}
					Wenda.closeWin();
				});
			}else{//活动分享
				//RegExp
				/*
				var beg = content.indexOf("【");
				var end = content.lastIndexOf("】");
				
				//alert(beg+" "+end);
				var title = content.substring(16,39);
				*/
				var tag = '';
				if(!pid){
					tag = '';
				}else{
					tag = pid ? "活动-"+pid : "";
				}
				
				var p_title = "";
				if(pid && pid > 0){
					var start = content.indexOf("【");
					var end = content.indexOf("】");
					
					p_title = content.substring(start+1,end);
					p_title = "查看相关活动：<a href='"+basePath+"party/detail.action?pid="+pid+"&index=1'>"+p_title+"</a>";
				}
				
				WendaAsk.saveAsk("json/questionJsonAction!addShare.action",content,p_title,tag,1,'','',window.location.href);
			}
		}
	}

	function modaldialogOper(title){
		$("#share_question").find("a[name='cancel']").bind("click",function(){
			setmodaldialog(title,"none");
		});
		setmodaldialog(title,"block");
	}
	/**
	 * 设置文本输入框的高度
	 * @param content
	 * @param $obj
	 */
	function setTextareaHeight(content,$obj){
		if($.browser.msie){
			if($obj.attr("onpropertychange")== null || $obj.attr("onpropertychange") == ""){
				$obj.attr("onpropertychange","this.style.posHeight=this.scrollHeight");
			}
			return ;
		}
		if($("#test-div")==""){
			$("body").append("<div id=\"test-div\" style=\"display:none;\"></div>");
		}
		var l = content.split("\n").length;
		$("#test-div").width(388+4);
		$("#test-div").html(content);
		var len = $("#test-div").height()+l*(21);
		
		if(len > 66){
			$obj.height(len);
		}
		$obj.focus();
	}
	/**
	 * 设置对话框的显示和标题
	 * 
	 * @param title
	 * @param showhide
	 */
	function setmodaldialog(title, showhide) {
		$("#modal-dialog").css("display", showhide);
		if (showhide != "none") {
			$("#modal-dialog").draggable({
				handle : "div#modalheader"
			});
			$("#modal-dialog-title-text").text(title);
		} else {
			$("div.modal-shadow").hide();
		}
	}
};
var sendInnerUserLisObj = {};

